numpy
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split
from sklearn.metrics import r2_score
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
import metrics
import seaborn as sns
#import warnings
#warnings.filterwarnings("ignore")
#%matplotlib inline
plt.rcParams['font.sans-serif']=['SimHei']
#⽤来正常显示中⽂标签
plt.rcParams['axes.unicode_minus'] = False
#⽤来正常显示负号 #有中⽂出现的情况，需要u'内容'
title_name_df=pd.read_excel(r"C:\0408-预测-Downloads\defintion.xlsx")
title_name=[]
for index,row in title_name_df.iterrows():
    title_name.append(row[1])
data = pd.read_csv(r'C:\0408-预测-Downloads\L2_Week3(1).csv',names=title_name,skiprows=1)
print(data)
sns.heatmap(data.corr(numeric_only=True))
#plt.show()
X = data.iloc[:,0:9]
marital = pd.get_dummies(X['婚姻状态'])
job = pd.get_dummies(X['职业']).astype(float)
default = pd.get_dummies(X['花呗是否有违约'])
returned = pd.get_dummies(X['是否有过退货'])
loan = pd.get_dummies(X['是否使用花呗结账'])
XX = pd.concat([X,job,marital,default,returned,loan],axis=1)
XXX = pd.concat([XX,data['该次活动中是否有使用优惠券']],axis=1)
sns.heatmap(XXX.corr(numeric_only=True))
#plt.show()
import warnings
warnings.filterwarnings("ignore")
x = [2,3,4,5,6]
XX.drop(XX.columns[x], axis=1, inplace=True)
XX_train,XX_test,Y_train,Y_test = train_test_split(XX,data['该次活动中是否有使用优惠券'],train_size=0.75)
model = LogisticRegression(C=1e4,random_state=100,class_weight='balanced')
model.fit(XX_train, Y_train)
prob = model.predict_proba(XX_train)
p=pd.DataFrame(prob).apply(lambda x:round(x,4))
print(p)
pred = model.predict(XX_test)
print(classification_report(Y_test,pred,labels=[1,0],target_names=['是','否']))
confusion = confusion_matrix(Y_test,pred)
plt.matshow(confusion,cmap=plt.cm.Blues, alpha=0.8)
plt.title('混淆矩阵')
plt.colorbar()
plt.ylabel('预测')
plt.xlabel('实际')
plt.show()
print('截距为:',model.intercept_)
print('回归系数为:',model.coef_)
print('训练集正确率',model.score(XX_train,Y_train))
#print('预测值正确率',metrics.accuracy_score(Y_test,pred))
from sklearn.metrics import roc_curve,auc
fpr,tpr,threshold = roc_curve(Y_test,pred)
roc_auc = auc(fpr,tpr)
print('ROC曲线AUC值:',roc_auc)
plt.figure(figsize=(6, 5))
# 绘制ROC曲线。
plt.plot(fpr, tpr, label="ROC")
# 绘制（0， 0）与（1， 1）两个点的连线，该曲线（直线）为随机猜测的效果。
plt.plot([0,1], [0,1], lw=2, ls="--", label="随机猜测")
# 绘制（0， 0）， （0， 1）， （1， 1）三点的连线（两条线），这两条线构成完美的roc曲线（auc的值为1）。
plt.plot([0, 0, 1], [0, 1, 1], lw=2, ls="-.", label="完美预测")
plt.xlim(-0.01, 1.02)
plt.ylim(-0.01, 1.02)
plt.xticks(np.arange(0, 1.1, 0.1))
plt.yticks(np.arange(0, 1.1, 0.1))
plt.xlabel('False Positive Rate(FPR)', fontsize=13)
plt.ylabel('True Positive Rate(TPR)', fontsize=13)
plt.grid()
plt.title(f"ROC曲线-AUC值为{auc(fpr, tpr):.5f}", fontsize=14)
plt.legend()
plt.show()